package com.example.message2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

//import com.example.message2.LoginActivity.UserLoginTask;

public class register extends Activity {
	String user = "";
	String password = "";

	String mEmail = "";
	String mPassword = "";
	static final String EXTRA_MESSAGE2 = "";

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private EditText mPasswordView2;

	String pass1 = "";
	String pass2 = "";
	static final String EXTRA_MESSAGE = "";
	private static final String PHP_REG = "http://softeng.cs.uwosh.edu/students/cs342g2/php/register.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		// Show the Up button in the action bar.

		// Set up the login form.

		mEmailView = (EditText) findViewById(R.id.editUser);

		mPasswordView = (EditText) findViewById(R.id.editPass);

		mPasswordView2 = (EditText) findViewById(R.id.confirmPass);

		findViewById(R.id.registerBtn2).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {

						String user = mEmailView.getText().toString();
						String password = mPasswordView.getText().toString();
						String confPassword = mPasswordView2.getText()
								.toString();
						View focusView = null;

						StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
								.permitAll().build();
						StrictMode.setThreadPolicy(policy);

						if (password.equals(confPassword)) {
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost(
									"http://softeng.cs.uwosh.edu/students/cs342g2/php/register.php");
							try { // Add your data
								List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
										2);
								nameValuePairs.add(new BasicNameValuePair(
										"uid", user));
								nameValuePairs.add(new BasicNameValuePair(
										"password", password));
								// nameValuePairs.add(new BasicNameValuePair(
								// "confpassword", password));
								httppost.setEntity(new UrlEncodedFormEntity(
										nameValuePairs));
								// Execute HTTP Post Request
								HttpResponse response = httpclient
										.execute(httppost);
								String result = EntityUtils.toString(response
										.getEntity());
								if (!result.equals("Success")) {
									Context context = getApplicationContext();
									Toast toast = Toast.makeText(context,
											result, Toast.LENGTH_LONG);
									toast.show();
									
									Intent myIntent = new Intent(register.this, MainActivity.class);
									startActivityForResult(myIntent, 0);
									//close();
									register.this.finish();
									
									
								} else {
									// new update().execute(user);
									// changeUser(user);
								}

							} catch (ClientProtocolException e) { // TODO
																	// Auto-generated
																	// catch
																	// block

							} catch (IOException e) { // TODO Auto-generated
														// catch
														// block } }
							}
						}else{
							Context context = getApplicationContext();
							Toast toast = Toast.makeText(context, "Your passwords do not match, register has failed.", Toast.LENGTH_LONG);
							toast.show();
						}
						// }
						// else{Toast.makeText(getApplicationContext(),
						// "cant connect", Toast.LENGTH_LONG).show();}
					}
				});
		// private void tryRegister(String username, String password) {

		findViewById(R.id.cancelBtn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent myIntent = new Intent(register.this, MainActivity.class);
						startActivityForResult(myIntent, 0);
						//close();
						register.this.finish();
						
					}
				});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void close() {
		this.finish();
		// Intent myIntent = new Intent(this, MainActivity.class);
		// myIntent.putExtra(EXTRA_MESSAGE, "false");
		// startActivityForResult(myIntent, 0);
	}

	public class UserRegisterTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if (networkInfo != null && networkInfo.isConnected()) {
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(2);
				n.add(new BasicNameValuePair("uname", params[0]));
				n.add(new BasicNameValuePair("password", params[1]));

				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_REG);
				// httppost.setEntity(new UrlEncodedFormEntity(n));

				try {
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost,
							respondHandler);
					success = true;

				} catch (Exception e) {

				}
			}

			return success;
		}

	}
}
